#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/4/13  12:52
# @Author: 余浪人
# @email: yulangren520@gmail.com
import os
from flask import request, jsonify
from flask_login import login_required
from apps.cms import cms_bp
from apps.lib.public import get_uuid_16, get_date_str, log
from apps.setting import Config, ProductionConfig
from apps import get_sys_uri


# 单文件上传
@cms_bp.route('/upload', endpoint='upload', methods=['POST'])
@login_required
def Ckupload():
    error = ''
    img_s = ['.png', '.jpg', '.jpeg']  # 允许上传图片文件类型
    if request.method == 'POST' and request.url_root == ProductionConfig.HOST + '/':
        fileobj = request.files['upload']  # 获取文件
        fname, fext = os.path.splitext(fileobj.filename)  # fext 为文件格式
        rnd_name = '%s%s' % (get_uuid_16(), fext)  # 文件名字
        fileCls = "images/" if fext.lower() in img_s else "files/"  # 判断文件类型
        base_path = os.path.join(get_sys_uri(), 'apps')
        relative_path = os.path.join(Config.FILE_PATH, fileCls, get_date_str(), rnd_name)  # 相对路径
        abs_path = base_path + '/static/' + relative_path  # 拼接路径
        # 检查路径是否存在，不存在则创建
        dirname = os.path.dirname(abs_path)
        if not os.path.exists(dirname):
            try:
                os.makedirs(dirname)
            except:
                error = '创建目录失败!'
        elif not os.access(dirname, os.W_OK):
            error = '没有写入权限!'
        if not error:
            fileobj.save(abs_path)
            log('上传文件')
            return jsonify({"uploaded": 1, "fileName ": fname + fext, "url": relative_path})
    else:
        error = '未知请求错误!'  # 请求错误
    return jsonify({"uploaded": 0, "error": {"message": error}})


# 图片上传
@cms_bp.route('/upload_img', endpoint='upload_img', methods=['POST'])
@login_required
def upload():
    error = ''
    img_s = ['.png', '.jpg', '.jpeg', '.bmp']  # 允许上传图片文件类型
    if request.method == 'POST':
        file = request.files['file']
        fname, fext = os.path.splitext(file.filename)  # fext 为文件格式
        rnd_name = '%s%s' % (get_uuid_16(), fext)  # 文件名字
        fileCls = "images/" if fext.lower() in img_s else "files/"  # 判断文件类型
        base_path = os.path.join(get_sys_uri(), 'apps')
        relative_path = os.path.join(Config.FILE_PATH, fileCls, get_date_str(), rnd_name)  # 相对路径
        abs_path = base_path + '/static/' + relative_path  # 拼接路径
        # 检查路径是否存在，不存在则创建
        dirname = os.path.dirname(abs_path)
        if not os.path.exists(dirname):
            try:
                os.makedirs(dirname)
            except:
                error = '创建目录失败!'
        elif not os.access(dirname, os.W_OK):
            error = '没有写入权限!'
        if not error:
            file.save(abs_path)
            log('上传文件')
            return jsonify({"status": 0, "img_url": relative_path})
    else:
        error = '未知请求错误!'  # 请求错误
        return jsonify({"status": 1, "message": error})
